package com.budwk.app.waterquality.services.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.budwk.app.sys.models.Sys_user;
import com.budwk.app.utils.PoiUtil;
import com.budwk.app.utils.StrUtil;
import com.budwk.app.waterquality.component.CommonComponent;
import com.budwk.app.waterquality.models.ScoreInfo;
import com.budwk.app.waterquality.services.ScoreInfoService;
import com.budwk.app.waterquality.vo.ScoreInfoQueryReqVo;
import com.budwk.starter.common.page.PageUtil;
import com.budwk.starter.common.page.Pagination;
import com.budwk.starter.database.service.BaseServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.xssf.streaming.SXSSFCell;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.util.cri.SqlExpressionGroup;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.List;

@IocBean(args = {"refer:dao"})
public class ScoreInfoServiceImpl extends BaseServiceImpl<ScoreInfo> implements ScoreInfoService {
    public ScoreInfoServiceImpl(Dao dao) {
        super(dao);
    }

    @Override
    public Pagination listByPage(ScoreInfoQueryReqVo reqVo) {
        Cnd cnd = buildQueryCondtiton(reqVo);
        return this.listPage(reqVo.getPageNo(), reqVo.getPageSize(), cnd);
    }

    @Override
    public String generateRatingReport(ScoreInfoQueryReqVo reqVo, HttpServletResponse response) throws IOException {
        XSSFWorkbook workbook = new XSSFWorkbook(PoiUtil.getInputStream("/formTemplate/file/score/generateRatingReport.xlsx"));
        SXSSFWorkbook book = new SXSSFWorkbook(workbook, 100);
        Cnd cnd = buildQueryCondtiton(reqVo);
        List<ScoreInfo> list = this.query(cnd);
        if (CollectionUtil.isEmpty(list)) {
            return PoiUtil.getDownFileUrl(System.currentTimeMillis() + ".xlsx", book, response);
        }
        // 获取样式
        CellStyle cellStyle = PoiUtil.getCellStyle(book);
        SXSSFSheet sheet = book.getSheetAt(0);
        int rowIndex = 1;
        for (ScoreInfo s : list) {
            SXSSFRow row = sheet.createRow(rowIndex);
            List<Object> cellDatas = List.of(s.getYear(), StrUtil.formatStrNull(s.getJcName()), s.getOriginalRecords(),
                    s.getReorgResultScore(), s.getQualityControl(), s.getExternalWork(),
                    s.getOtherRecords(), s.getTotalScore(), s.getRemark());
            // 序号
            SXSSFCell cell = row.createCell(0);
            cell.setCellValue(rowIndex);
            cell.setCellStyle(cellStyle);
            // 组装数据
            int cellIndex = 1;
            for (Object cellData : cellDatas) {
                SXSSFCell cell1 = row.createCell(cellIndex);
                cell1.setCellValue(String.valueOf(cellData));
                cell1.setCellStyle(cellStyle);
                cellIndex ++;
            }
            rowIndex ++;
        }
        return PoiUtil.getDownFileUrl(System.currentTimeMillis() + ".xlsx", book, response);
    }

    @Override
    public void create(ScoreInfo scoreInfo) {
        Sys_user user = CommonComponent.getCurrentUser();
        LocalDateTime submitDate = scoreInfo.getSubmitDate();
        if (submitDate == null) {
            submitDate = LocalDateTime.now();
        }
        String year = LocalDateTimeUtil.format(submitDate, DatePattern.NORM_YEAR_PATTERN);
        scoreInfo.setYear(year);
        scoreInfo.setCreateId(user.getId()).setCreateDate(LocalDateTime.now())
                .setUpdateDate(LocalDateTime.now()).setUpdateId(user.getId())
                .setSubmitDate(LocalDateTime.now());
        this.insert(scoreInfo);
    }

    private Cnd buildQueryCondtiton(ScoreInfoQueryReqVo reqVo) {
        Cnd cnd = Cnd.NEW();
        SqlExpressionGroup where = cnd.where();
        if (Strings.isNotBlank(reqVo.getPageOrderBy())) {
            cnd.orderBy(reqVo.getPageOrderName(), PageUtil.getOrder(reqVo.getPageOrderBy()));
        }
        if (StringUtils.isNotEmpty(reqVo.getQueryYear())) {
            where.andEquals(ScoreInfo::getYear, reqVo.getQueryYear());
        }
        return cnd;
    }



}
